#include "../include/client.h"
#define MAX 1000

int recvFile(int sockFd, const char *filename)
{
    //先判断本地有没有，如果有，查看一下大小
    //如果本地已经有了，并且
    //如果没有或者上次传输没传完
    
    int dataLen = 0;
    int fileSize = 0;
    int pos = 0; //断点续传的偏移量
    int recvSize = 0;
    int recvRet = 0;
    char md5str[128] = {0};
    char localMD5[128] = {0};
    Train_t train;
    
    //根据文件名打开文件
    int fd = open(filename, O_RDWR|O_CREAT, 0666);

    //1、接收文件大小
    recv(sockFd, &dataLen, 4, 0);
    recv(sockFd, &fileSize, dataLen, 0);

    //2、接收文件的MD5码
    recv(sockFd, &dataLen, 4, MSG_WAITALL);
    recv(sockFd, md5str, dataLen, MSG_WAITALL);

    //获取本地文件的大小，用来判断，求出偏移值
    struct stat fileInfo;
    fstat(fd, &fileInfo);
    pos = (int)fileInfo.st_size;

    if(pos == fileSize){
        //如果大小一样，判断文件是否一致
        Compute_file_md5(filename, localMD5);
        //文件一致就不再下载
        if(strcmp(localMD5, md5str) == 0){
            //通知服务器不下载了
            send(sockFd, "q", 1, 0);
            printf("%s is already exist!\n", filename);
            return 1;
        }
        //文件不一致就从头开始下载
        pos = 0;
    }
    else if(pos > fileSize){
        //文件不一样，直接从头开始下载
        pos = 0;
    }

    //3、通知服务器开始下载
    send(sockFd, "c", 1, 0);

    //4、把偏移值发送给服务器，并开始接收文件内容
    memset(&train, 0, sizeof(train));
    train.dataLen = 4;
    memcpy(train.buf, &pos, train.dataLen);
    send(sockFd, &train, 4+train.dataLen, 0);

    //5、偏移文件的指针，然后开始接收文件内容
    int fdPipe[2];
    pipe(fdPipe);

    lseek(fd, pos, SEEK_SET);
    recvSize = pos;

    while(recvSize < fileSize){
        recvRet = splice(sockFd, 0, fdPipe[1], 0, MAX, 0);
        recvRet = splice(fdPipe[0], 0, fd, 0, MAX, 0);
        ERROR_CHECK(recvRet, -1, "splice");
        if(0 == recvRet){
            //意外中断
            printf("server exit!\n");
            break;
        }
        recvSize += recvRet;
    }
    close(fd);
    close(fdPipe[0]);
    close(fdPipe[1]);

    return 0;
}

